package org.example.chapter5.controller;

import org.example.chapter5.entity.Student;
import org.example.chapter5.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/api")
public class StudentController {

    @Autowired
    private StudentMapper studentMapper;

    // 统一的响应方法
    private ResponseEntity<?> response(boolean success, String message, Object data) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        result.put("message", message);
        if (data != null) {
            result.put("data", data);
        }
        return ResponseEntity.ok(result);
    }

    // 验证学生信息
    private String validateStudent(Student student) {
        if (student.getName() == null || student.getName().trim().isEmpty()) {
            return "用户名不能为空";
        }
        if (student.getQq() == null || student.getQq().trim().isEmpty()) {
            return "QQ号不能为空";
        }
        return null;
    }

    // 注册
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody Student student) {
        String error = validateStudent(student);
        if (error != null) {
            return response(false, error, null);
        }

        try {
            if (studentMapper.findByName(student.getName()) != null) {
                return response(false, "注册失败，用户名已存在", null);
            }
            studentMapper.insert(student);
            return response(true, "注册成功", null);
        } catch (Exception e) {
            return response(false, "注册失败：" + e.getMessage(), null);
        }
    }

    // 登录
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginInfo) {
        String name = loginInfo.get("name");
        String qq = loginInfo.get("qq");

        if (name == null || qq == null) {
            return response(false, "用户名和QQ号不能为空", null);
        }

        Student student = studentMapper.findByName(name);
        if (student != null && student.getQq().equals(qq)) {
            return response(true, "登录成功", student);
        }
        return response(false, "登录失败，用户名或QQ号错误", null);
    }

    // 更新
    @PutMapping("/students/{id}")
    public ResponseEntity<?> updateStudent(@PathVariable("id") Integer id, @RequestBody Student student) {
        String error = validateStudent(student);
        if (error != null) {
            return response(false, error, null);
        }

        try {
            Student existingStudent = studentMapper.findById(id);
            if (existingStudent == null) {
                return response(false, "更新失败，用户不存在", null);
            }

            Student studentWithNewName = studentMapper.findByName(student.getName());
            if (studentWithNewName != null && !Objects.equals(id, studentWithNewName.getId())) {
                return response(false, "更新失败，新用户名已存在", null);
            }

            student.setId(id);
            studentMapper.update(student);
            return response(true, "更新成功", null);
        } catch (Exception e) {
            return response(false, "更新失败：" + e.getMessage(), null);
        }
    }

    // 删除
    @DeleteMapping("/students/{id}")
    public ResponseEntity<?> deleteStudent(@PathVariable("id") Integer id) {
        try {
            Student student = studentMapper.findById(id);
            if (student == null) {
                return response(false, "删除失败，用户不存在", null);
            }
            studentMapper.deleteById(id);
            return response(true, "删除成功", null);
        } catch (Exception e) {
            return response(false, "删除失败：" + e.getMessage(), null);
        }
    }
}